<!-- eslint-disable @typescript-eslint/no-unused-vars -->
<!-- eslint-disable no-void -->
<script setup lang="ts">
  import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
  import SvgIcon from '@/components/SvgIcon/index.vue'
  import { NTooltip, NEllipsis, NInput, useMessage } from 'naive-ui'
  // import type { HistoryList } from '../types'
  import { CREATE_DIALOG } from '../utils/constant'
  import { deleteConversation, getHistory, renameConversation } from '@/api/agent'
  import DeleteModal from '@/components/common/DeleteModal/index.vue'
  import { useAgent } from '@/hooks/useAgent'
  const { userName } = useAgent()
  const showHistoryList = ref(true)
  const curItemId = ref('1')
  const props = defineProps<{
    isSending: boolean
  }>()

  onMounted(async () => {
    await getHistoryFn()
    addClickOutside()
  })

  onBeforeUnmount(() => {
    removeClickOutside()
  })

  const addClickOutside = () => {
    document.addEventListener('click', onClickOutside)
  }

  const removeClickOutside = () => {
    document.removeEventListener('click', onClickOutside)
  }

  // 事件监听器（同步）
  const onClickOutside = (_e: MouseEvent) => {
    void handleClickOutside()
  }

  // 真正的异步处理逻辑
  const handleClickOutside = async () => {
    if (editItemId.value) {
      const obj = list.value.find((item: any) => item.id === editItemId.value)
      if (obj) {
        obj.showEdit = false
        if (obj.name !== obj.historyName) {
          await handleEditConfirm(obj)
        }
      }
    }
  }

  const getMore = ref(true)
  const lastId = ref<string | undefined>(undefined)
  const getHistoryFn = async () => {
    const res = await getHistory({
      user: userName,
      limit: 30,
      sort_by: '-created_at',
      last_id: lastId.value,
    })
    res.forEach((item: any) => {
      item.showEdit = false
      item.historyName = item.name
    })
    list.value = [...list.value, ...res]
    lastId.value = res[res.length - 1].id
    if (res.length < 30) {
      getMore.value = false
    }
  }

  const list = ref<any[]>([])
  const historyList = computed(() => {
    // 最近半年
    const now = new Date()
    const sixMonthsAgo = new Date(now.getTime() - 6 * 30 * 24 * 60 * 60 * 1000)
    // 半年前的数据
    const sixMonthsAgoData = list.value.filter((item: any) => {
      const createTime = new Date(+item.created_at * 1000)
      return createTime < sixMonthsAgo
    })
    // 最近半年
    const sixMonthsData = list.value.filter((item: any) => {
      const createTime = new Date(+item.created_at * 1000)
      return createTime >= sixMonthsAgo
    })
    return [
      {
        list: sixMonthsData,
        time: '最近半年',
      },
      {
        list: sixMonthsAgoData,
        time: '更久之前',
      },
    ]
  })

  const historyListRef = ref<HTMLElement | null>(null)
  const handleScroll = async () => {
    // 滚动到底部则调接口
    if (historyListRef.value) {
      const scrollTop = historyListRef.value.scrollTop
      const scrollHeight = historyListRef.value.scrollHeight
      const clientHeight = historyListRef.value.clientHeight
      if (scrollTop + clientHeight >= scrollHeight && getMore.value) {
        await getHistoryFn()
      }
    }
  }

  const emit = defineEmits(['createDialog', 'clickItem', 'rename', 'deleteItem'])
  const createNewDialog = (params?: any) => {
    const obj = {
      id: params?.id ?? new Date().getTime().toString(),
      name: params?.name ?? '新对话',
      created_at: new Date().getTime(),
      isNew: true,
    }
    if (params?.lastId) {
      list.value = list.value.filter((item: any) => item.id !== params.lastId)
    }
    list.value.unshift(obj)
    curItemId.value = obj.id
  }

  const handleCreateDialog = () => {
    if (props.isSending) return
    createNewDialog()
    emit('createDialog', curItemId.value)
  }

  const handleClickItem = (item: any) => {
    if (props.isSending) return
    curItemId.value = item.id
    emit('clickItem', item)
  }

  const editItemId = ref<any>(null)
  const handleEdit = (item: any) => {
    if (props.isSending) return
    editItemId.value = item.id
    item.showEdit = true
  }
  const message = useMessage()
  const handleEditConfirm = async (item: any) => {
    await renameConversation({
      conversation_id: item.id,
      name: item.name,
    })
    message.success('重命名成功')
    item.showEdit = false
    editItemId.value = null
    emit('rename', item)
  }

  const deleteItemId = ref<any>(null)
  const handleDelete = (item: any) => {
    if (props.isSending) return
    deleteItemId.value = item.id
    deleteModalRef.value?.showModal(`确定删除会话【${item.name}】吗？`)
  }

  const deleteModalRef = ref()
  const handleDeleteConfirm = async () => {
    await deleteConversation({
      conversation_id: deleteItemId.value,
      name: userName,
    })
    message.success('删除成功')
    list.value = list.value.filter((item: any) => item.id !== deleteItemId.value)

    if (deleteItemId.value === curItemId.value) {
      curItemId.value = ''
      emit('deleteItem')
    }
    deleteItemId.value = null
  }
  defineExpose({
    createNewDialog,
  })
</script>

<template>
  <div
    class="w-[296px] h-full bg-white rounded-lg py-6 px-4 pingfang"
    :class="{ '!w-16': !showHistoryList }"
  >
    <div
      @click="showHistoryList = !showHistoryList"
      class="h-8 leading-8 w-8 hover:bg-[#EFF1F5] rounded flex items-center justify-center"
    >
      <SvgIcon v-if="!showHistoryList" class="text-[32px] cursor-pointer" name="fold-in" />
      <SvgIcon v-else class="text-[32px] cursor-pointer" name="fold-out" />
    </div>
    <div class="mt-4">
      <div
        @click="handleCreateDialog"
        class="h-8 leading-8 w-[116px] create-dialog text-[#0B5CFF] rounded flex items-center pl-1 cursor-pointer"
        :class="{ '!text-[#666D7A] !w-8 justify-center pl-0 hide-name': !showHistoryList }"
      >
        <SvgIcon v-if="showHistoryList" class="text-[32px]" name="edit" />
        <n-tooltip v-else placement="right" :show-arrow="false">
          <template #trigger>
            <SvgIcon class="text-[32px]" name="edit" />
          </template>
          <span class="text-[#FEFEFE] text-[12px] pingfang">{{ CREATE_DIALOG }}</span>
        </n-tooltip>
        <div class="ml-1" v-show="showHistoryList">
          <span class="text-[16px] font-medium">{{ CREATE_DIALOG }}</span>
        </div>
      </div>
    </div>
    <div
      class="history-list mt-6"
      ref="historyListRef"
      v-show="showHistoryList"
      @scroll="handleScroll"
    >
      <div class="history-list-item" v-for="item in historyList" :key="item.time">
        <div
          v-show="item.list.length > 0"
          class="history-list-item-time h-9 leading-9 text-[#666D7A] font-bold px-2"
        >
          {{ item.time }}
        </div>
        <div class="chat-item-list">
          <div
            @click="handleClickItem(o)"
            class="chat-item h-9 relative leading-9 px-3 cursor-pointer text-[#666D7A] rounded hover:bg-[#F6F6F6]"
            v-for="o in item.list"
            :key="o.id"
            :class="{ 'bg-[#F2F6FA] !text-[#0B5CFF] font-bold': curItemId === o.id && !o.showEdit }"
          >
            <div v-show="!o.showEdit">
              <n-ellipsis class="chat-item-name" :line-clamp="1">{{ o.name }}</n-ellipsis>
              <n-tooltip placement="right" class="more-tooltip" trigger="click" :show-arrow="false">
                <template #trigger>
                  <SvgIcon
                    @click.stop
                    :class="{ '!text-white': curItemId === o.id }"
                    class="text-[24px] absolute right-3 top-1/2 -translate-y-1/2 more-icon text-[transparent]"
                    name="more"
                  />
                </template>
                <div class="cursor-pointer rounded-lg text-[#000000] pingfang text-[14px]">
                  <div
                    @click.stop="handleEdit(o)"
                    class="h-8 leading-8 px-2 hover:bg-[#F5F5F5] flex items-center"
                  >
                    <SvgIcon class="text-[16px] mr-1" name="rename" />
                    <span>重命名</span>
                  </div>
                  <div
                    @click.stop="handleDelete(o)"
                    class="h-8 leading-8 px-2 hover:bg-[#F5F5F5] flex items-center"
                  >
                    <SvgIcon class="text-[16px] mr-1" name="delete" />
                    <span>删除</span>
                  </div>
                </div>
              </n-tooltip>
            </div>
            <div v-show="o.showEdit" @click.stop>
              <n-input
                maxlength="20"
                type="text"
                @keydown.enter="handleEditConfirm(o)"
                v-model:value="o.name"
                class="w-full h-8 leading-8 px-3 rounded-lg"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
    <DeleteModal ref="deleteModalRef" @submit="handleDeleteConfirm" />
  </div>
</template>

<style lang="less" scoped>
  .create-dialog {
    background-color: #dbeafe;
  }

  .hide-name {
    background-color: transparent;

    &:hover {
      background-color: #eff1f5;
    }
  }

  .history-list {
    height: calc(100% - 96px);
    overflow-y: auto;

    .more-icon {
      display: none;
    }

    .chat-item:hover {
      .more-icon {
        display: block;
      }
    }
  }
</style>
